<template>
  <el-tabs type="border-card" class="user-settings-tabs">
    <!-- 个人信息标签页 -->
    <el-tab-pane label="个人信息">
      <el-card class="setting-card">
        <template #header>
          <div class="card-header">
            <span>个人信息管理</span>
          </div>
        </template>

        <el-form 
          ref="profileFormRef" 
          :model="profileForm" 
          :rules="profileRules" 
          label-width="120px"
        >
          <el-form-item label="用户名:" prop="userAccount">
            <el-input v-model="profileForm.userAccount" placeholder="请输入姓名" />
          </el-form-item>

          <el-form-item label="真实姓名:" prop="userName">
            <el-input v-model="profileForm.userName" placeholder="请输入真实姓名" />
          </el-form-item>

          <el-form-item label="公司:" prop="userCompany">
            <el-input v-model="profileForm.userCompany" placeholder="请输入公司" />
          </el-form-item>

          <el-form-item label="电话:" prop="userTelephone">
            <el-input v-model="profileForm.userTelephone" placeholder="请输入电话" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitProfile">确认修改</el-button>
            <el-button @click="resetProfile">取消修改</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-tab-pane>

    <!-- 密码修改标签页 -->
    <el-tab-pane label="密码修改">
      <el-card class="setting-card">
          <template #header>
          <div class="card-header">
              <span>密码修改</span>
          </div>
          </template>

          <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="120px"
          >
          <el-form-item label="旧密码" prop="oldPwd">
              <el-input 
              v-model="passwordForm.oldPwd" 
              type="password" 
              show-password 
              placeholder="请输入旧密码"
              />
          </el-form-item>

          <el-form-item label="新密码" prop="newPwd">
              <el-input 
              v-model="passwordForm.newPwd" 
              type="password" 
              show-password 
              placeholder="请输入新密码"
              />
          </el-form-item>

          <el-form-item label="确认密码" prop="rePwd">
              <el-input 
              v-model="passwordForm.rePwd" 
              type="password" 
              show-password 
              placeholder="请确认新密码"
              />
          </el-form-item>

          <el-form-item>
              <el-button type="primary" @click="submitPassword">确认修改</el-button>
              <el-button @click="resetPassword">取消修改</el-button>
          </el-form-item>
          </el-form>
      </el-card>
    </el-tab-pane>
  </el-tabs>
</template>

<script setup>
  import { ref, reactive,onBeforeMount } from 'vue'
  import { ElMessage } from 'element-plus'
  import { 
    EditUserInfoServer,
    PasswordServer 
  } from '@/api/instance'
  import { nextTick } from 'vue'
  import { useUserStore } from '@/stores'
  import { storeToRefs } from 'pinia'


  // 用户信息表单数据
  const profileForm = reactive({
    userId: 0,
    userAccount: '',
    userName: '',
    userCompany: '',
    userTelephone: '',
  })
  const profileFormRef = ref(null)

  // 密码表单数据
  const passwordForm = reactive({
    oldPwd: '',
    newPwd: '',
    rePwd: ''
  })
  const passwordFormRef = ref(null)

  const userStore = useUserStore()
  const { userInfo } = storeToRefs(userStore)

  // 表单验证规则
  const profileRules = {
    userAccount: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 1, max: 16, message: '长度1-16位', trigger: 'blur' },
    ],
    userName: [
      { required: true, message: '请输入真实姓名', trigger: 'blur' },
      { min: 2, max: 16, message: '长度2-16位', trigger: 'blur' },
    ],
    userCompany: [
      { required: false, message: '请输入公司名称', trigger: 'blur' },
      { min: 0, max: 16, message: '长度0-16位', trigger: 'blur' },
    ],
    userTelephone: [
      { required: false, message: '请输入电话号码', trigger: 'blur' },
      { pattern: /^\d{11}$/, message: '长度11位', trigger: 'blur' },
    ],//电话未设置复杂的验证过程，可以酌情添加
  }

  const passwordRules = {
    oldPwd: [
      { required: true, message: '请输入旧密码', trigger: 'blur' },
      { min: 8, message: '长度大于等于8位', trigger: 'blur' },
    ],
    newPwd: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 8, message: '长度大于等于8位', trigger: 'blur' },
    ],
    rePwd: [
      { required: true, message: '请确认密码', trigger: 'blur' },
      { 
        validator: (rule, value) => {
          return value === passwordForm. newPwd
        },
        message: '两次输入密码不一致',
        trigger: 'blur'
      }
    ]
  }

  // 初始化用户信息
  onBeforeMount(async () => {
    try {
        // await 
        userStore.getUserInfo();
        // console.log('获取用户信息:', profileForm)
        // console.log('存储用户信息:',userInfo.value)
        Object.assign(profileForm,userInfo.value)//会改变吗？留意
    } catch (error) {
      ElMessage.error('修改个人信息窗口请求失败')
    }
  })

  // 提交个人信息
  const submitProfile = async () => {
    if (!profileFormRef.value) return
    await profileFormRef.value.validate(async valid => {
      if (valid) {
        try {
          // 必须包含所有可更新字段（根据接口文档 1.4）
          const res = await EditUserInfoServer({
            userId: profileForm.userId, // 必须字段
            userAccount: profileForm.userAccount,
            userName: profileForm.userName,
            userCompany: profileForm.userCompany,
            userTelephone: profileForm.userTelephone,
          })
          if (res.code === 0) {
            ElMessage.success('个人信息修改成功')
            // 同步原始数据
            userStore.updateUserInfo(profileForm);
          } else {
            ElMessage.error(res.message || '更新失败')
          }
        } catch (error) {
          ElMessage.error(error+'网络请求失败1')
        }
      }
    })
  }
  // 重置个人信息
  const resetProfile = () => {
    Object.assign(profileForm, userInfo.value);
    nextTick(() => { // 确保 DOM 更新后再执行
        profileFormRef.value?.clearValidate();
        // console.log('重置成功',profileForm);
    });
    // console.log('重置成功完成后',profileForm);
  }

  // 提交密码修改
  const submitPassword = async () => {
    if (!passwordFormRef.value) return
    await passwordFormRef.value.validate(async valid => {
      if (valid) {
        try {
          // 必须包含 oldPwd/newPwd/rePwd（根据接口文档 1.5）
          const res = await PasswordServer({
            oldPwd: passwordForm.oldPwd,
            newPwd: passwordForm.newPwd,
            rePwd: passwordForm.rePwd // 必须传递
          })
          if (res.code === 0) {
            ElMessage.success('密码修改成功')
            resetPassword() // 清空表单
          } else {
            ElMessage.error(res.message || '修改失败')
          }
        } catch (error) {
          ElMessage.error(error+'网络请求失败2')
        }
      }
    })
  }

  // 重置密码表单
  const resetPassword = () => {
    // passwordForm.oldPwd = ''
    // passwordForm.newPwd = ''
    // passwordForm.rePwd = ''
    nextTick(() => { // 确保 DOM 更新后再执行
        passwordFormRef.value?.resetFields();
    });
  }
</script>

<style lang="scss" scoped>
  .user-settings-tabs{
    height: 95%;
    width: 95%;
    margin: 15px auto;//原来为20px，现在为15px
    .setting-card{
      height: 95%;
      margin: 20px;
      .card-header{
        font-size: 18px;
        font-weight: bold;
      }
    }
  }
  .el-tab-pane {
    height:100%;
  }
  .el-form {
    padding: 20px;
  }
  .el-form-item {
    margin-bottom: 60px; /* 原默认值为 25px，可调大数值 */
    margin-right:45%;
    margin-left:5%;
  }
</style>